<template>
  <div>
    <div class="request" v-if="!addShow && !dtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-if="route.name === 'Outorder'"
          v-hasPermi="['system:outorder:query']"
          class="btn search"
          @click="getList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-if="route.name === 'OutorderAudit'"
          v-hasPermi="['system:outorderAudit:query']"
          class="btn search"
          @click="getList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >

        <el-button
          v-if="route.name === 'Outorder'"
          v-hasPermi="['system:outorder:add']"
          class="btn search"
          @click="(addShow = true), (pageType = 'add');"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="deliveryApplyCode">出库编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantDate">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicant">申请人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">申请部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deliveryTypeDict">出库类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deliveryUsageTypeDict">用途类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="purchaseApplyCode">关联请购单</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectCode">关联项目</el-checkbox>
            </div>
            <div>
              <el-checkbox label="latestDeliverDate">最晚交付日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="approvalStatusDict">审核状态</el-checkbox>
            </div>
            <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div>
            <div v-if="route.name === 'OutorderAudit'">
              <el-checkbox label="deliveryStatusDict">出库状态</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item" style="margin-bottom: 10px">
          <el-input
            clearable
            v-model="params.deliveryApplyCode"
            class="search-input"
            placeholder="请输入出库编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.applicant"
            class="search-input"
            placeholder="请输入申请人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.projectCode"
            class="search-input"
            placeholder="请输入项目编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.deliveryType"
            placeholder="请选择出库类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in outStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <el-select
            v-model="params.deliveryUsageType"
            placeholder="请选择用途类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in deliveryStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <el-select
            v-model="params.approvalStatus"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in auditStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div
          class="search-item"
          v-if="route.name === 'OutorderAudit'"
          v-hasPermi="['system:outorderAudit:list']"
        >
          <el-select
            v-model="params.deliveryStatus"
            placeholder="请选择出库状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in eliveryStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="list"
        border
        height="59.2vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <el-table-column label="操作" width="150px">
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-if="
                  route.name === 'Outorder' &&
                  [3, 4, 6].includes(row.approvalStatus)
                "
                v-hasPermi="['system:outorder:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'Outorder' && [0].includes(row.approvalStatus)
                "
                v-hasPermi="['system:outorder:revoke']"
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('revoke', row)"
              >
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>

              <el-icon
                v-hasPermi="['system:outorder:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'OutorderAudit' &&
                  [0, 1, 5].includes(row.approvalStatus) &&
                  row.auditStatus == 1
                "
                v-hasPermi="['system:outorderAudit:list']"
                title="审核"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('audit', row)"
              >
                <Checked />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'OutorderAudit' &&
                  row.approvalStatus == 5 &&
                  row.deliveryStatus == 0
                "
                v-hasPermi="['system:outorderAudit:check']"
                title="出库"
                color="#0000FF"
                class="table-icon"
                :size="20"
                @click="handleOperate('check', row)"
              >
                <img
                  src="@/assets/icons/images/outbound.png"
                  style="width: 16px; height: 18px"
                />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'Outorder' &&
                  [3, 6].includes(row.approvalStatus)
                "
                v-hasPermi="['system:outorder:delete']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'OutorderAudit' &&
                  [3].includes(row.approvalStatus) &&
                  false
                "
                v-hasPermi="['system:outorderAudit:delete']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="80"
          align="center"
        />
        <el-table-column
          label="出库编号"
          prop="deliveryApplyCode"
          v-if="checkList.includes('deliveryApplyCode')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />
        <el-table-column
          label="申请日期"
          prop="applicantDate"
          v-if="checkList.includes('applicantDate')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />

        <el-table-column
          label="申请人"
          prop="applicant"
          v-if="checkList.includes('applicant')"
          :show-overflow-tooltip="true"
          width="100"
          sortable="custom"
        />
        <el-table-column
          label="申请部门"
          prop="deptName"
          v-if="checkList.includes('deptName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="出库类型"
          prop="deliveryTypeDict"
          v-if="checkList.includes('deliveryTypeDict')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />
        <el-table-column
          label="用途类型"
          prop="deliveryUsageTypeDict"
          v-if="checkList.includes('deliveryUsageTypeDict')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />

        <el-table-column
          label="关联请购单"
          prop="purchaseApplyCode"
          v-if="checkList.includes('purchaseApplyCode')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        >
          <template #default="{ row }">
            <span
              v-if="row.purchaseApplyId"
              @click="handlepurchaseRequestDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.purchaseApplyCode }}</span
            >
            <span v-else>{{ row.purchaseApplyCode }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="关联项目"
          prop="projectCode"
          v-if="checkList.includes('projectCode')"
          :show-overflow-tooltip="true"
          width="180"
          sortable="custom"
        >
          <template #default="{ row }">
            <span
              v-if="row.projectId"
              @click="handleProjectDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.projectCode }}</span
            >
            <span v-else>{{ row.projectCode }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="最晚交付日期"
          prop="latestDeliverDate"
          v-if="checkList.includes('latestDeliverDate')"
          :show-overflow-tooltip="true"
          width="150"
          sortable="custom"
        />
        <el-table-column
          label="审核状态"
          prop="approvalStatusDict"
          v-if="checkList.includes('approvalStatusDict')"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.approvalStatusDict)">{{
              row.approvalStatusDict
            }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="下步流程"
          prop="nextNodeName"
          v-if="checkList.includes('nextNodeName')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          v-if="
            route.name === 'OutorderAudit' &&
            checkList.includes('deliveryStatusDict')
          "
          label="出库状态"
          prop="deliveryStatusDict"
          :show-overflow-tooltip="true"
          width="130"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getList"
      />
    </div>

    <OutorderAdd
      ref="outorderAddRef"
      v-if="addShow"
      v-model:addShow="addShow"
      @refreshList="getList"
      :pageType="pageType"
    />
    <OutorderDtl
      ref="outorderDtlRef"
      v-if="dtlShow"
      v-model:dtlShow="dtlShow"
      @refreshList="getList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import OutorderDtl from "./dtl.vue";
import OutorderAdd from "./add.vue";
import { getDictsApi } from "@/api/dict";
import {
  getOutorderListApi,
  deleteDelivery,
  editDeliveryApi,
} from "@/api/stock/outorder";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 路由
const route = useRoute();
const router = useRouter();
// 搜索参数
const params = reactive({
  deliveryApplyCode: "", //出库编号
  applicant: "", //申请人
  projectCode: "", //项目编号
  deliveryType: null, //出库类型
  deliveryUsageType: null, //用途类型
  approvalStatus: null, //审核状态
  deliveryStatus: null, //出库状态
  pageNum: 1,
  pageSize: 50,
  approvalStatusCheck: null,
  sortField: "",
  sortOrder: "",
});
// 表格加载效果
const loading = ref(false);
// 数据list列表
const list = ref([]);
// 出库类型
const outStatusList = ref([]);
// 审核状态
const auditStatusList = ref([]);
//用途类型
const deliveryStatusList = ref([]);
//出库状态
const eliveryStatusList = ref([]);
// 总数
const total = ref(0);
// 出库新增组件引用
const outorderAddRef = ref(null);
// 出库查看组件引用
const outorderDtlRef = ref(null);
// 出库新增组件显隐
const addShow = ref(false);
// 出库查看组件显隐
const dtlShow = ref(false);
// 操作类型
const pageType = ref("");

const checkList = ref([
  "deliveryApplyCode",
  "applicantDate",
  "applicant",
  "deptName",
  "deliveryTypeDict",
  "deliveryUsageTypeDict",
  "purchaseApplyCode",
  "projectCode",
  "latestDeliverDate",
  "approvalStatusDict",
  "nextNodeName",
  "deliveryStatusDict",
]);

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: route.name === "Outorder" ? 28 : 29,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: route.name === "Outorder" ? 28 : 29,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    deliveryApplyCode: "", //出库编号
    applicant: "", //申请人
    projectCode: "", //项目编号
    deliveryType: null, //出库类型
    deliveryUsageType: null, //用途类型
    approvalStatus: null, //审核状态
    deliveryStatus: null, //出库状态
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getList();
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getList();
};

/**
 * @description: 获取出库列表
 */
const getList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    if (route.name === "Outorder") {
      params.approvalStatusCheck = null;
      params.type = 1;
    } else {
      params.approvalStatusCheck = 1;
      params.type = 2;
    }
    const res = await getOutorderListApi({ pageNum, pageSize }, params);
    list.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 表格操作(0-待审核,1-审核中,2-未通过,3-已撤销,4-已驳回,5-已通过,6-未提交)
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      addShow.value = true;
      nextTick(() => {
        outorderAddRef.value.handleDetailInfo(row.deliveryApplyId);
      });
      break;
    case "revoke":
      let obj = {
        deliveryApplyId: row.deliveryApplyId,
        approvalStatus: 3,
      };
      ElMessageBox.confirm("确定撤销该数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await editDeliveryApi(obj);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "detail":
      pageType.value = type;
      dtlShow.value = true;
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo(row.deliveryApplyId, row);
      });
      break;
    case "audit":
      pageType.value = type;
      dtlShow.value = true;
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo(row.deliveryApplyId, row);
      });
      break;
    case "check":
      pageType.value = type;
      dtlShow.value = true;
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo(row.deliveryApplyId, row);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该出库信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteDelivery(row.deliveryApplyId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

/**
 * @description: 获取字典
 */
async function getDicts() {
  //出库类型
  await getDictsApi("erp_delivery_type").then((res) => {
    if (res.code === 200) {
      outStatusList.value = res.data;
    }
  });

  // 审核状态
  await getDictsApi("erp_delivery_apply_approval_status").then((res) => {
    if (res.code === 200) {
      if (route.name === "Outorder") {
        auditStatusList.value = res.data;
      } else {
        auditStatusList.value = res.data.filter((status) => status.value !== 6);
      }
    }
  });

  // 用途类型
  await getDictsApi("erp_delivery_usage_type").then((res) => {
    if (res.code === 200) {
      deliveryStatusList.value = res.data;
    }
  });
  // 出库状态
  if (route.name === "OutorderAudit") {
    await getDictsApi("delivery_status").then((res) => {
      if (res.code === 200) {
        eliveryStatusList.value = res.data;
      }
    });
  }
}
/* 跳转项目详情 */
const handleProjectDetail = (row) => {
  const { href } = router.resolve({
    path: `/sales/project`,
    query: { projectId: row.projectId },
  });
  window.open(href, "_blank");
  // window.open(`/sales/project?projectId=${row.projectId}`, "_blank");
};

/* 跳转请购详情 */
const handlepurchaseRequestDetail = (row) => {
  const { href } = router.resolve({
    path: `/purchase/purchaseRequest`,
    query: { purchaseApplyId: row.purchaseApplyId },
  });
  window.open(href, "_blank");
  // window.open(
  //   `/purchase/purchaseRequest?purchaseApplyId=${row.purchaseApplyId}`,
  //   "_blank"
  // );
};
onMounted(() => {
  // 路由携带项目id参数，直接显示详情页
  if (route.query?.deliveryApplyId) {
    let deliveryApplyId = route.query.deliveryApplyId;
    pageType.value = "detail";
    dtlShow.value = true;
    nextTick(() => {
      outorderDtlRef.value.handleDetailInfo(deliveryApplyId, {
        approvalStatus: 5,
      });
    });
  }
  if (route.query?.applyId) {
    let applyId = route.query.applyId;
    pageType.value = "detail";
    dtlShow.value = true;
    nextTick(() => {
      outorderDtlRef.value.handleDetailInfo(applyId, {
        approvalStatus: 5,
      });
    });
  }
  if (route.query?.businessId) {
    let applyId = route.query.businessId;
    if (
      route.query.checkStatus === "待审核" ||
      route.query.checkStatus === "审核中"
    ) {
      pageType.value = "audit";
      dtlShow.value = true;
      nextTick(() => {
        outorderDtlRef.value.handleDetailInfo(Number(applyId), {
          approvalStatus: 1,
        });
      });
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId;
    pageType.value = "detail";
    dtlShow.value = true;
    nextTick(() => {
      outorderDtlRef.value.handleDetailInfo(Number(applyId), {
        approvalStatus: 5,
      });
    });
  }
  getDicts();
  getList();
  getTableHeader();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
  .search {
    flex-wrap: wrap;
  }
}
</style>
